﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ModelLayer;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace CinemaDbLib
{
	public class MovieDB
	{
		private Connection connection;

		public MovieDB()
		{
			connection = new Connection();
		}

		public List<Movie> getMovies()
		{
			return where("");
		}

		public Movie getMovieById(int id)
		{
			return singleWhere("id = " + id);
		}

		private Movie singleWhere(String wClause)
		{
			Movie movie = null;

			string query = "SELECT * FROM Movies WHERE " + wClause;
			connection.Open();
			SqlDataReader reader = connection.Read(query);

			if (reader.Read())
			{
				movie = new Movie();
				movie.id = reader.GetInt32(0);
				movie.name = reader.GetString(1);
				movie.genre = reader.GetString(2);
				movie.description = reader.GetString(3);
			}

			reader.Close();
			connection.Close();

			return movie;
		}

		private List<Movie> where(String wClause)
		{
			List<Movie> movies = new List<Movie>();
			string query;
			if (!wClause.Equals(""))
				query = "SELECT * FROM Movies WHERE " + wClause;
			else
				query = "SELECT * FROM Movies";
			connection.Open();
			SqlDataReader reader = connection.Read(query);

			while (reader.Read())
			{
				Movie movie = new Movie();
				movie.id = reader.GetInt32(0);
				movie.name = reader.GetString(1);
				movie.genre = reader.GetString(2);
				movie.description = reader.GetString(3);
				movies.Add(movie);
			}

			reader.Close();
			connection.Close();

			return movies;
		}
	}
}
